<?php

namespace app\admin\controller;

use app\admin\traits\Backend;

class Department extends \app\admin\controller\Backend
{
    protected $model = null;
    private $searchFields = ['name', 'status'];
    use Backend;

    protected $needSelectCompany = true;
    protected $beforeActionList = [
        'getCurrentCompany',
        'permitNew' => ['only' => 'save'],
    ];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Department();
    }

    public function index()
    {
        $this->existModel();
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [];
        if ($this->request->param('query')) {
            $where ['name'] = ['like', '%' . $this->request->param('query') . '%'];
        }
        $where['company_id'] = $this->getCurrentCompany()->id;
        $where['is_del']=0;
        $list = $this->model
            ->with(['parentDepartment'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $this->assign("tree",$this->model->getTree($this->getCurrentCompany()->id));
        $this->assign('list', $list);
        $this->assign('params', [
            'query' => $this->request->param('query'),
        ]);
        return $this->fetch('index');
    }
    public function add(){
        // print_r(Request()->param());die;
        $data=Request()->param();
        $data['company_id']=$this->getCurrentCompany()->id;
        $data['create_time']=time();
        $res=db('department')->insert($data);
        if($res){
            return $this->success('成功',url('index'));
        }else{
            return $this->error('失败',url('index'));
        }
    }
}